# -*- coding: utf-8 -*-
"""
Description: 请求重试装饰器
"""

import time
import requests
from functools import wraps
import urllib3

urllib3.disable_warnings()
def retry_on_failure(max_retries=3, delay=1):
    """
    请求重试装饰器
    :param max_retries: 最大重试次数
    :param delay: 重试间隔时间（秒）
    """

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < max_retries:
                try:
                    response = func(*args, **kwargs)
                    # 检查响应状态码
                    if 200 <= response.status_code < 300:
                        return response
                    print(
                        f"请求失败，状态码: {response.status_code}，第 {retries + 1} 次重试..."
                    )
                except requests.RequestException as e:
                    print(f"请求异常: {str(e)}，第 {retries + 1} 次重试...")

                retries += 1
                if retries < max_retries:
                    time.sleep(delay * retries)  # 指数退避
            raise Exception(f"达到最大重试次数 {max_retries}，请求失败")

        return wrapper

    return decorator


@retry_on_failure(max_retries=4, delay=6)
def post_request(**kwargs):
    """
    发送POST请求

    Args:
        url (str): 请求URL
        headers (dict, optional): 请求头
        cookies (dict, optional): cookies
        data (dict, optional): 请求数据
        **kwargs: 其他requests.post()支持的参数

    Returns:
        Response: requests响应对象
    """
    return requests.post(**kwargs)

@retry_on_failure(max_retries=4, delay=6)
def get_request(**kwargs):
    """
    发送GET请求
    """
    return requests.get(**kwargs)